﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using StockMatch.Service;
using StockMatch.Service.Entity;
using StockMatch.WebSite.Models;
using Titan;

namespace StockMatch.WebSite.Controllers
{
    public class StockController : StockControllerBase
    {
        public ActionResult Index(string param)
        {
            ViewBag.Menu = "stock";
            Stock stock = new Stock();
            if (!string.IsNullOrEmpty(param))
            {
                string[] ps = param.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                stock.Principal = decimal.Parse(ps[0].Split('=')[1]);
                stock.MatchEndowment = int.Parse(ps[1].Split('=')[1]);
                stock.TotalTrade = decimal.Parse(ps[2].Split('=')[1]);
                stock.LossWarLine = decimal.Parse(ps[3].Split('=')[1]);
                stock.LossOpenLine = decimal.Parse(ps[4].Split('=')[1]);
                stock.FundTime = int.Parse(ps[5].Split('=')[1]);
                stock.LoanMoon = decimal.Parse(ps[6].Split('=')[1]);
                stock.StartTime = int.Parse(ps[7].Split('=')[1]);
            }
            else
            {
                stock.Principal = 0;
                stock.MatchEndowment = 0;
            }
            return View(stock);
        }
        public ActionResult Banner()
        {
            return View();
        }

        public ActionResult Scroll()
        {
            return View();
        }

        public ActionResult Confirm(Stock stock)
        {
            stock.Number = Guid.NewGuid().ToString();
            var result = MathProject.GetScheme(stock.MatchEndowment, stock.FundTime,stock.MatchEndowment/stock.Principal,0);
            stock.TotalTrade = stock.MatchEndowment + stock.Principal;
            stock.LossWarLine = result.WarningLine;
            stock.LossOpenLine = result.OpenLine;
            if (CurrentUser != null)
            {
                User user = ServiceManager.UserService.GetUser(CurrentUser.UserId);
                ViewBag.BalanceAmount = user.BalanceAmount;
            }
            ViewBag.Menu = "stock";
            return View(stock);
        }

        public ActionResult PostConfirm(Stock stock)
        {
            if (stock == null)
            {
                throw new ArgumentNullException("stock");
            }
            if (CurrentUser == null)
            {
                return Json(new { data = 2, message = "请先登录" });
            }
            Project project = new Project();
            var result = MathProject.GetScheme(stock.MatchEndowment, stock.FundTime, stock.MatchEndowment / stock.Principal, 0);
            project.UserId = CurrentUser.UserId;
            project.Principal = stock.Principal;//投资本金
            project.MatchEndowment = stock.MatchEndowment;//配资金额
            project.TotalTrade = stock.MatchEndowment + stock.Principal;//总操盘资金
            project.LossWarLine = result.WarningLine;//亏损警告线
            project.LossOpenLine = result.OpenLine;//亏损平仓线
            project.FundTime = stock.FundTime;//资金使用期限（按月）
            project.StartTime = stock.StartTime;
            DateTime nextDate = DateTime.Now.AddDays(1);
            project.StartProjectTime = project.StartTime == 0
                ? DateTime.Now
                : new DateTime(nextDate.Year, nextDate.Month, nextDate.Day, 9, 0, 0);//下个交易日
            project.LoanMoon = stock.LoanMoon;
            project.AddTime = DateTime.Now;
            project.ProjectState = (int) ProjectStateEnum.CapitalVerification;
            project.Proportion = 100;//盈利全归你

            User user = ServiceManager.UserService.GetUser(CurrentUser.UserId);
            if (user.BalanceAmount < project.TotalTrade)
            {
                return Json(new { data = 3, message = "账户余额不足" });
            }
            if (ServiceManager.ProjectService.Insert(project))
            {
                return Json(new { data = 1, message = "ok" });
            }
            return Json(new { data = 0, message = "提交方案失败" });
        }

        public ActionResult Seccess(int id)
        {
            Project project = ServiceManager.ProjectService.GetProject(id);
            return View(project);
        }


        public ActionResult Project(int id)
        {
            Project project = ServiceManager.ProjectService.GetProject(id);
            if (project == null)
            {
                return View("~/Views/Stock/Project404.cshtml");
            }
            #region 追加本金记录
            QueryExpression query = new QueryExpression();
            query.EntityType = typeof(ProjectPrincipal);
            query.Select(ProjectPrincipal_.ALL);
            query.Where(ProjectPrincipal_.ProjectId.TEqual(project.ProjectId));
            query.OrderBy(ProjectPrincipal_.AddTime.Asc);
            ProjectPrincipals projectPrincipals = ServiceManager.ProjectPrincipalService.GetProjectPrincipals(query);
            ViewData["ProjectPrincipal"] = projectPrincipals;
            ViewData["ProjectPrincipal0"] = projectPrincipals.Items.Where(p => p.AddState == 1).ToList();
            #endregion
            return View(project);
        }

        [HttpPost]
        public ActionResult AddRiskMargin(int projectId, int riskMargin, int type)
        {
            if (riskMargin < 100)
            {
                return Json(new { data = 0, message = "追加的本金金额不能小于100元" });
            }
            if (CurrentUser == null)
            {
                return Json(new { data = 0, message = "请先登录" });
            }
            if (ServiceManager.UserService.GetUser(CurrentUser.UserId).BalanceAmount < riskMargin)
            {
                return Json(new { data = 0, message = "账户余额不足，请充值" });
            }
            int i = ServiceManager.ProjectService.AddPrincipal(projectId, riskMargin, type);
            if (i == 2)
            {
                return Json(new { data = 0, message = "每天最多追加5次(包括取消次数)" });
            }
            if (i > 0)
            {
                return Json(new { data = 1, message = "申请追加本金成功" });
            }
            return Json(new { data = 0, message = "申请追加本金失败" });
        }
    }
}